package model;


import java.io.File;

import com.ibm.staf.STAFHandle;
import com.ibm.staf.STAFMarshallingContext;
import com.ibm.staf.STAFResult;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ScriptExecutionThread extends Thread {

    private TestScript script;
    private boolean reset;
    private static STAFHandle handle;

    public ScriptExecutionThread(TestScript script) {
        this.script = script;
    }

    private String getPathCopyLogTemplate() {
        return getTemplateFolderPath() + "\\copylog.xml";
    }

    private String getPwd() {
        try {
            File pwd = new File(".");
//            System.out.println(pwd.getCanonicalFile());
            return pwd.getCanonicalPath();
        } catch (IOException ex) {
            Logger.getLogger(ScriptExecutionThread.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    private String getTemplateFolderPath() {
        return getPwd() + "\\template";
    }

    private String getPathOfCleanTSExecutionTemplate() {
        return getTemplateFolderPath() + "\\rft.xml";
    }

    private String getPathOfDefaultTSExecutionTemplate() {
        return getTemplateFolderPath() + "\\somke.xml";
    }

    private String wrapWithQuote(String stupidPathWithBlack) {
        stupidPathWithBlack = stupidPathWithBlack.replace("\\", "/");
        return "\"" + stupidPathWithBlack + "\"";
    }

    public void run2() {
        STAFResult result;

        try {
            handle = new STAFHandle("runScript");
            if (reset) {
                result = handle.submit2("local", "stax", "execute file " +
                        wrapWithQuote(getPathOfDefaultTSExecutionTemplate()) + " args \"{'machine':'" +
                        this.script.getMachine() + "','script':" + wrapWithQuote(this.script.getScriptPath()) + "}\" jobname " +
                        this.script.getJobName() + " wait returnresult");
            } else {
                result = handle.submit2("local", "stax", "execute file " +
                        wrapWithQuote(getPathOfCleanTSExecutionTemplate()) + " args \"{'machine':'" +
                        this.script.getMachine() + "','script':\\\"" + this.script.getScriptPath().replace("\\", "/") + "\\\"}\" jobname " +
                        this.script.getJobName() + " wait returnresult");
            }
            handle.unRegister();
            if (result.rc == 0) {
                if (STAFMarshallingContext.isMarshalledData(result.result)) {
                    STAFMarshallingContext mc = STAFMarshallingContext.unmarshall(
                            result.result);
                    HashMap hash = (HashMap) mc.getRootObject();
//                    Iterator it = hash.keySet().iterator();
//                    while(it.hasNext()){
//                        String key = (String)it.next();
//                        System.out.println("["+key+"]="+hash.get(key).toString());
//                    }
//                    System.out.println(hash.get("result"));
                    if (hash.get("result").equals("Bingo") && copyLog()) {
                        this.script.setState(TestScript.STATE_COMPLETED_OK);
                        if (this.script.getResult().isPassed()) {
                            System.out.println("Passed");
                        } else {
                            System.out.println("Failed");
                        }
                    } else {
                    }
                }
            } else {
                System.out.println(result.result);
            }
            updateStatus();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void run1(){
        STAFResult result;
        try {
            handle = new STAFHandle("TSH_"+this.script.getScriptName());
            result = handle.submit2("local", "rft", "runscript \"" +
                    this.script.getScriptPath().replace("\\", "\\\\") + "\" wait returnstdout stderrtostdout");
            handle.unRegister();
            if (result.rc == 0) {
                if (STAFMarshallingContext.isMarshalledData(result.result)) {
                    STAFMarshallingContext mc = STAFMarshallingContext.unmarshall(
                            result.result);
                    HashMap hash = (HashMap) mc.getRootObject();
                    HashMap item = (HashMap) ((LinkedList) hash.get("fileList")).get(0);
                    if (item.get("rc").toString().equals("0")) {
                        copyLog();
                        script.setState(TestScript.STATE_COMPLETED_OK);
                    }
                }else{
                    System.out.println(result.result);
                    script.setState(TestScript.STATE_COMPLETED_ERR);
                }
            }
            if(result.rc==16){
                throw new VMNotReadyException();
            }
            else {
                System.out.println(result.result);
                System.out.println(result.rc);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void run(){
    	STAFResult result;
    	try{
    		handle = new STAFHandle("TSH_"+this.script.getScriptName());
    		String scriptname = this.script.getScriptName();
    		String cmd = "java -classpath \\\"C:/Program Files/IBM/SDP70/FunctionalTester/bin/rational_ft.jar\\\" com.rational.test.ft.rational_ft -datastore \\\"C:/install_script/installer_scripts\\\" -playback " + scriptname;
    		result = handle.submit2("win03uepinstall", "process", "start command \"" + cmd + "\"" + " stderrtostdout returnstdout wait");
    		//result = handle.submit2("win03uepinstall", "process", "start command \"java -classpath \\\"C:/Program Files/IBM/SDP70/FunctionalTester/bin/rational_ft.jar\\\" com.rational.test.ft.rational_ft -datastore \\\"C:/install_script/installer_scripts\\\" -playback Script2\" stderrtostdout returnstdout wait");
    		handle.unRegister();
    		if (result.rc == 0) {
                if (STAFMarshallingContext.isMarshalledData(result.result)) {
                    STAFMarshallingContext mc = STAFMarshallingContext.unmarshall(
                            result.result);
                    HashMap hash = (HashMap) mc.getRootObject();
                    HashMap item = (HashMap) ((LinkedList) hash.get("fileList")).get(0);
                    if (item.get("rc").toString().equals("0")) {
                        copyLog();
                        script.setState(TestScript.STATE_COMPLETED_OK);
                    }
                }else{
                    System.out.println(result.result);
                    script.setState(TestScript.STATE_COMPLETED_ERR);
                }
            }
            if(result.rc==16){
                throw new VMNotReadyException();
            }
            else {
                System.out.println(result.result);
                System.out.println(result.rc);
            }
            updateStatus();
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    private String getLocalHostName() {
        try {
            InetAddress addr = InetAddress.getLocalHost();

            // Get IP Address
//            byte[] ipAddr = addr.getAddress();
//            System.out.println(new String(ipAddr));
//            return new String(ipAddr);

            // Get hostname
            String hostname = addr.getHostName();
            return hostname;
        } catch (UnknownHostException e) {
            return null;
        }

    }

    private boolean copyLog() {
        try {
            handle = new STAFHandle("copyLog");
            STAFResult result = handle.submit2(this.script.getMachine(), "fs", "copy directory \"" +
                    this.script.getLogPath().replace("\\", "/") + "\" tomachine " + getLocalHostName() +
                    " todirectory \"" + this.script.getServerSideLogPath().replace("\\", "/") + "\" recurse");
            handle.unRegister();
            if (result.rc == 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception ex) {
            Logger.getLogger(ScriptExecutionThread.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

    }

    private void updateStatus() {
        script.setState(TestScript.STATE_COMPLETED_OK);
    }
    
    public static void main(String[] args){
    	TestScript ts;
		try {
			ts = new TestScript("Script2","win03uepinstall","staf2");
			ScriptExecutionThread SET = new ScriptExecutionThread(ts);
			SET.run();
		} catch (InvalidVMHostNameException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   
    }
}

